#include "stdafx.h"

#include "ListItemsDlg.h"
#include "ItemViewDlg.h"

#define MZ_IDC_VIEW			101
#define MZ_IDC_TOOLBAR		102

CItemViewDlg g_ItemViewDlg;

CItemViewDlg::CItemViewDlg()
{
}

CItemViewDlg::~CItemViewDlg()
{
}

BOOL CItemViewDlg::OnInitDialog()
{
	if(!CMzWndEx::OnInitDialog()) return FALSE;

    mView.SetPos(0, 0, GetWidth(), GetHeight()-MZM_HEIGHT_TEXT_TOOLBAR);
    mView.SetID(MZ_IDC_VIEW);
    AddUiWin(&mView);
	mView.SetReadOnly(true);

	mToolbar.SetPos(0, GetHeight()-MZM_HEIGHT_TEXT_TOOLBAR, GetWidth(), MZM_HEIGHT_TEXT_TOOLBAR);
    mToolbar.SetID(MZ_IDC_TOOLBAR);
    mToolbar.SetButton(0, true, true, L"Return");
    mToolbar.SetButton(1, false, true, L"Update");
    mToolbar.SetButton(2, false, true, L"Login");
    AddUiWin(&mToolbar);

	return TRUE;
}

void CItemViewDlg::OnMzCommand(WPARAM wParam, LPARAM lParam)
{
	UINT_PTR id = LOWORD(wParam);

	if(id==MZ_IDC_TOOLBAR) {
		switch(lParam) {
		case 0:
			g_ListItemsDlg.Active(MZ_ANIMTYPE_SCROLL_LEFT_TO_RIGHT_1);
			break;
		case 1:
			break;
		case 2:
			break;
		}
	}
}

void CItemViewDlg::Active(UINT nAnimType, int nCID)
{
	if(nCID!=-1) {
		Item I;
		if(!CReaderDatabase::GetSingleton().GetItem(nCID, I)) {
			mView.SetText(_T("ERROR in GetItem"));
		} else {
			LPTSTR pBody = (LPTSTR)malloc(400*1024);
			if(!Utf8ToTCHAR(I.summary.c_str(), pBody, 400*1024)) {
				mView.SetText(_T("ERROR in Utf8ToCHAR"));
			} else {
				mView.SetText(_T(""));
				LPTSTR pCur = pBody;
				TCHAR cFind = _T('<');
				LPTSTR pFind;
				for(;;) {
					pFind = _tcschr(pCur, cFind);
					if(pFind==NULL) break;
					if(cFind==_T('<')) {
						*pFind = _T('\0');
						mView.InsertString(pCur);
						*pFind = _T('<');
						if(		memcmp(pFind, _T("<br>"), 4*sizeof(TCHAR))==0
							||	memcmp(pFind, _T("</p>"), 4*sizeof(TCHAR))==0) {
							mView.InsertString(_T("\n"));
							pCur = pFind + 4;
						} else {
							pCur = pFind;
							cFind = _T('>');
						}
						continue;
					}
					if(cFind==_T('>')) {
						if(memcmp(pCur, _T("<img"), 4*sizeof(TCHAR))==0) {
							LPTSTR pSrc = _tcsstr(pCur, _T("src=\""));
							if(pSrc!=NULL && pSrc<pFind) {
								pSrc += 5;
								LPTSTR pEnd = _tcschr(pSrc, _T('\"'));
								if(pEnd!=NULL && pEnd<pFind) {
									pCur = pEnd + 1;
									*pEnd = _T('\0');
									mView.AddImage(_T("\\Disk\\Debug\\RSSReader\\a.jpg"));
									mView.InsertString(_T("[[IMG("));
									mView.InsertString(pSrc);
									mView.InsertString(_T(")IMG]]"));
								}
							}
						}
						pCur = pFind + 1;
						cFind = _T('<');
						continue;
					}
				}
				mView.InsertString(pCur);
			}
			free(pBody);
			mView.ScrollTo(0);
		}
	}

    if(MzGetParam(MZGP_APP_START_ANIMATION)==TRUE) {
		AnimateWindow(nAnimType, true);
    }
	Show();
}
